package com.chunfen.dubbo.protocol.http;

import com.chunfen.dubbo.framework.Invocation;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpClient {

    public Map<String, ? extends Serializable> post(String hostName, Integer port, Invocation invocation){

        Map<String, ? extends Serializable> stringMap = null;

        try{

            // 向 服务端发送请求  调用服务
            URL url = new URL("http", hostName, port, "/");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);

            OutputStream out = urlConnection.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(out);

            oos.writeObject(invocation);
            oos.flush();
            oos.close();


            // 处理回送 数据   处理返回值
            InputStream is = urlConnection.getInputStream();
            ObjectInputStream oin = new ObjectInputStream(is);

            stringMap = (Map<String, ? extends Serializable>) oin.readObject();

            oin.close();



        } catch (Exception e){
            e.printStackTrace();
        }

        return  stringMap;
    }
}
